package cn.wildfire.chat.app.extendsion.classes;

import android.app.Activity;
import android.content.Intent;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.InterfaceReceiversHub;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.wxapi.WXUserInfo;

import org.json.JSONObject;

import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.login.model.LoginResult;
import cn.wildfire.chat.app.main.LoginActivity;
import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfirechat.remote.ChatManager;

/**
 * Create by HEKE, 2019/10/15 15:40
 * TODO 微信账号登入
 */
public class WXLoginRequest {

    private Activity activity;
    private WXUserInfo wxUserInfo;

    public WXLoginRequest(Activity activity, WXUserInfo wxUserInfo) {
        this.activity = activity;
        this.wxUserInfo = wxUserInfo;
        req();
    }

    /**
     * 登入
     */
    protected void req() {
        if (wxUserInfo == null) {
            return;
        }
        try {
            MaterialDialog dialog = new MaterialDialog.Builder(activity)
                    .content(activity.getString(R.string.logining_msg))
                    .progress(true, 100)
                    .cancelable(false)
                    .build();
            dialog.show();

            OkHttpRequest.getNewInstance(activity).requestAsynJsonObject2(ServerUrlClient.WX_LOGIN, wxUserInfo.toNormalJson(), new ReqCallBack<String>() {
                @Override
                public void onReqSuccess(String result) {
                    System.out.println("########## WX Login result : " + result);
                    try {
                        dialog.dismiss();
                        String ret = result;
                        ResponseEntity<String, String> responseEntity = new ResponseEntity<>(result);
                        if (responseEntity.getErrorCode().equals("0")) {
                            LoginResult loginResult = new LoginResult();
                            JSONObject jsonObject = new JSONObject(ret);
                            JSONObject entry = jsonObject.getJSONObject("result");
                            loginResult.setToken(entry.getString("token"));
                            loginResult.setUserId(entry.getString("userId"));
                            String checkSetEncrypted = entry.getString("checkSetEncrypted");
                            // 设置账号对应缓存路径
                            Config.setCurrentLoginUserIdForCacheSet(loginResult.getUserId());
                            // 刷新和连接服务
                            ChatManagerHolder.gChatManager.connect(loginResult.getUserId(), loginResult.getToken());
                            // 保存账号密码、登录信息
                            SPUtils.setMuches(activity, "config",
                                    new String[]{"id", "token"}, new String[]{loginResult.getUserId(), loginResult.getToken()});
                            ChatManager.Instance().getUserInfo(loginResult.getUserId(), true);
                            // 注册推送账号
                            InterfaceReceiversHub.setMiPushAccount(activity, loginResult.getUserId());

                            if (activity instanceof LoginActivity) {
                                LoginActivity loginActivity = (LoginActivity) activity;
                                if ("0".equals(checkSetEncrypted)) {
                                    loginActivity.ShowPopWindow();
                                } else {
                                    //如果已经设置过密保
                                    // 进入主界面
                                    Intent intent = new Intent(activity, MainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    activity.startActivity(intent);
                                    activity.finish();
                                }
                            } else {
                                // 进入主界面
                                Intent intent = new Intent(activity, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                activity.startActivity(intent);
                                activity.finish();
                            }

                        } else {
                            JSONObject jsonObject = new JSONObject(ret);
                            String message = jsonObject.getString("message");
                            ToastTip.tip("登录失败!" + message);
                            activity.finish();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    dialog.dismiss();
                    System.out.println("###### errorMsg : " + errorMsg);
                    activity.finish();
                }
            }).request();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
